package cn.mumzone.pos.ui.fragment;

import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.base.BaseFragment;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.loading.button.LoadingButton;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.ToastUtil;
import cn.mumzone.pos.R;
import cn.mumzone.pos.dialog.PosDialog;
import cn.mumzone.pos.event.MoreViewChangeEvent;
import cn.mumzone.pos.model.ScheduleDetailEntity;
import cn.mumzone.pos.model.ScheduleEmployeeEntity;
import cn.mumzone.pos.model.ServerEntity;
import cn.mumzone.pos.presenter.SchedulePresenter;
import cn.mumzone.pos.presenter.contract.ScheduleContract;
import cn.mumzone.pos.ui.activity.ACT_ChangeShift;
import cn.mumzone.pos.ui.adapter.ADA_DialogChooseServerList;
import cn.mumzone.pos.ui.adapter.ADA_ScheduleEmployee;
import cn.mumzone.pos.ui.widgets.others.FullyGridLayoutManager;
import cn.mumzone.pos.ui.widgets.schedule.ScheduleView;


/**
 * Created by qiuzhenhuan on 2019/7/10.
 */

public class FRA_Schedule extends BaseFragment<SchedulePresenter> implements ScheduleContract.View {

    @BindView(R.id.sv_schedule)
    ScheduleView scheduleView;
    @BindView(R.id.ll_shift_list)
    LinearLayout llShiftList;
    @BindView(R.id.sv_shift_list)
    NestedScrollView scShiftList;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;

    private AlertDialog mAddEmployeeToShiftDialog;

    private LRecyclerView rvServerList;
    private ADA_DialogChooseServerList mServerAdapter;
    private LRecyclerViewAdapter mLrvServerAdapter;
    private List<ServerEntity> shopServerList;


    private AlertDialog mEmployeeDialog;
    private LoadingButton btnRemove;

    private ScheduleEmployeeEntity mSelectedEmployee;

    private ScheduleDetailEntity mSelectedSchedule;

    private boolean inActivity;


    @Override
    protected void initEventAndData() {

        scheduleView.setOnDateItemClickListener(new ScheduleView.OnDateItemClickListener() {
            @Override
            public void onDateItemClicked(String date) {
                mPresenter.getScheduleDetail(date);
            }
        });
        scheduleView.setNotScheduleEnable(true);
        initEmployeeDialog();

        initAddEmployeeToShiftDialog();

        mPresenter.getAllScheduleInfo();
        mPresenter.getScheduleDetail(scheduleView.getSelectedDate());
        mPresenter.getServerList();
        mPresenter.initEvent();
    }

    @Override
    public void showScheduleStatus(List<String> scheduleEntities) {
        scheduleView.setScheduleStatus(scheduleEntities);
    }

    @Override
    public void showScheduleDetail(List<ScheduleDetailEntity> scheduleDetailEntityList) {
        if(mEmployeeDialog!=null && mEmployeeDialog.isShowing()){
            btnRemove.stopLoading("移除");
            mEmployeeDialog.dismiss();
            PosToast.INSTANCE.makeCheckMarkToast(mContext, "已移除");
        }
        llShiftList.removeAllViews();
        if (!ListUtil.isListEmpty(scheduleDetailEntityList)) {
            scShiftList.setVisibility(View.VISIBLE);
            tvEmpty.setVisibility(View.GONE);
            for (final ScheduleDetailEntity entity : scheduleDetailEntityList) {
                View view = LayoutInflater.from(mContext).inflate(R.layout.view_shift, llShiftList, false);
                TextView tvShiftTime = view.findViewById(R.id.tv_shift_time);
                tvShiftTime.setText(String.format("%s - %s", AppDateUtil.getDateToString(Long.valueOf(entity.getScheduleStartTime()), "HH:mm"),
                        AppDateUtil.getDateToString(Long.valueOf(entity.getScheduleEndTime()), "HH:mm")));
                RecyclerView rvEmployee = view.findViewById(R.id.rv_employee);
                rvEmployee.setLayoutManager(new FullyGridLayoutManager(mContext, 3));
                ADA_ScheduleEmployee adapter = new ADA_ScheduleEmployee(mContext);
                adapter.setDataList(ListUtil.isListEmpty(entity.getScheduleWorkList()) ? new ArrayList<ScheduleEmployeeEntity>() : entity.getScheduleWorkList());
                rvEmployee.setAdapter(adapter);
                adapter.setHasAddButton(true);
                adapter.setOnItemClickListener(new ADA_ScheduleEmployee.OnItemClickListener() {
                    @Override
                    public void onItemClick(ScheduleEmployeeEntity employeeEntity, int position) {
                        mSelectedSchedule = entity;
                        if (employeeEntity != null) {
                            mSelectedEmployee = employeeEntity;
                            mEmployeeDialog.setText(R.id.tv_dialog_title, employeeEntity.getEmployeeName());
                            showDialog(mEmployeeDialog);
                        } else {
                            showAddEmployeeDialog();
                        }
                    }
                });
                llShiftList.addView(view);
            }
        } else {
            scShiftList.setVisibility(View.GONE);
            tvEmpty.setVisibility(View.VISIBLE);
        }

        if (mAddEmployeeToShiftDialog != null && mAddEmployeeToShiftDialog.isShowing()) {
            LoadingButton lbConfirm = mAddEmployeeToShiftDialog.getView(R.id.lb_confirm);
            lbConfirm.stopLoading("确定");
            mAddEmployeeToShiftDialog.dismiss();
            PosToast.INSTANCE.makeToast(mContext, PosToast.ToastType.TOAST_TYPE_SQUARE,
                    PosToast.ToastSquareLevel.ALERT_SUCCESS_SQUARE, "技师添加成功~", false);

        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            String selectedDay = AppDateUtil.getDateToString(System.currentTimeMillis(), "yyyy-MM-dd");
            scheduleView.setSelectedDate(selectedDay);
            mPresenter.getScheduleDetail(selectedDay);
            mPresenter.getServerList();
            mPresenter.getAllScheduleInfo();
        } else {
            scheduleView.clearCheck();
        }
    }

    private void initEmployeeDialog() {

        mEmployeeDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_schedule_employee)
                .setDialogNoConfirm()
                .setWidthAndHeight(328, 260)
                .create();
        btnRemove = mEmployeeDialog.getView(R.id.btn_delete);

        mEmployeeDialog.getView(R.id.btn_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPresenter.isNowSchedule(scheduleView.getSelectedDate(), mSelectedSchedule)) {
                    return;
                }
                btnRemove.startLoading("正在移除",mEmployeeDialog.getView(R.id.iv_dialog_close),
                        mEmployeeDialog.getView(R.id.btn_change_shift));
                mPresenter.removePersonFromShift(scheduleView.getSelectedDate(),
                        mSelectedEmployee.getScheduleId(), mSelectedEmployee.getEmployeeId(),
                        mSelectedSchedule.getScheduleStartTime(), mSelectedSchedule.getScheduleEndTime());
            }
        });
        mEmployeeDialog.getView(R.id.btn_change_shift).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPresenter.isNowSchedule(scheduleView.getSelectedDate(), mSelectedSchedule)) {
                    return;
                }
                mPresenter.checkEmployeeDoChangeShift(scheduleView.getSelectedDate(),
                        mSelectedEmployee.getScheduleId(), mSelectedEmployee.getEmployeeId(),
                        mSelectedSchedule.getScheduleStartTime(), mSelectedSchedule.getScheduleEndTime());
            }
        });

    }

    private void initAddEmployeeToShiftDialog() {
        mAddEmployeeToShiftDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_choose_server)
                .setDialogTitle("选择技师")
                .setWidthAndHeight(438, 350)
                .setOnSingleConfirmListener(new AlertDialog.Builder.OnSingleConfirmListener() {
                    @Override
                    public void onConfirmClicked(AlertDialog dialog) {

                        if (ListUtil.isListEmpty(mServerAdapter.getData())) {
                            closeDialog(mAddEmployeeToShiftDialog);
                            return;
                        }
                        if (ListUtil.isListEmpty(mServerAdapter.getSelectedServerList())) {
                            PosToast.INSTANCE.makeShortToast(mContext, "请先选择技师");
                            return;
                        }
                        LoadingButton lbConfirm = mAddEmployeeToShiftDialog.getView(R.id.lb_confirm);
                        lbConfirm.startLoading("正在添加", rvServerList, mAddEmployeeToShiftDialog.getView(R.id.iv_dialog_close));

                        StringBuilder builder = new StringBuilder();
                        for (int index = 0; index < mServerAdapter.getSelectedServerList().size(); index++) {
                            ServerEntity entity = mServerAdapter.getSelectedServerList().get(index);
                            builder.append(entity.getTechnicianId());
                            if (index < mServerAdapter.getSelectedServerList().size() - 1) {
                                builder.append(",");
                            }
                        }
                        mPresenter.addPresonShift(mSelectedSchedule, scheduleView.getSelectedDate(), builder.toString());
                    }
                }).create();
        rvServerList = mAddEmployeeToShiftDialog.getView(R.id.server_list);
        GridLayoutManager manager = new GridLayoutManager(mContext, 2);
        rvServerList.setLayoutManager(manager);
        mServerAdapter = new ADA_DialogChooseServerList(mContext);
        mServerAdapter.setDoubleCheck(true);
        mLrvServerAdapter = new LRecyclerViewAdapter(mServerAdapter);
        rvServerList.setAdapter(mLrvServerAdapter);
        GridItemDecoration divider = new GridItemDecoration.Builder(mContext)
                .setHorizontal(R.dimen.dp_22)
                .setVertical(R.dimen.dp_20)
                .setColorResource(android.R.color.transparent)
                .build();
        rvServerList.addItemDecoration(divider);

        rvServerList.setHasFixedSize(true);
        rvServerList.setPullRefreshEnabled(false);
        rvServerList.setLoadMoreEnabled(false);

    }

    public void showAddEmployeeDialog() {
        ArrayList<ServerEntity> noSelectedArray = new ArrayList<>();
        for (ServerEntity server : shopServerList) {
            boolean isSelected = false;
            if (!ListUtil.isListEmpty(mSelectedSchedule.getScheduleWorkList())) {
                for (ScheduleEmployeeEntity entity : mSelectedSchedule.getScheduleWorkList()) {
                    if (entity.getEmployeeId().equals(server.getTechnicianId())) {
                        isSelected = true;
                        break;
                    }
                }
            }
            if (!isSelected) {
                noSelectedArray.add(server);
            }
        }
        if (ListUtil.isListEmpty(noSelectedArray)) {
            mAddEmployeeToShiftDialog.toggleShowEmpty(true, R.id.root_view, R.drawable.svg_ic_empty_server, "暂无可选技师~");
        } else {
            mAddEmployeeToShiftDialog.toggleShowEmpty(false, R.id.root_view);
            mServerAdapter.setData(noSelectedArray);
            mLrvServerAdapter.notifyDataSetChanged();
        }
        mAddEmployeeToShiftDialog.show();
    }

    @OnClick({R.id.iv_back})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                if(inActivity){
                    getActivity().finish();
                }else {
                    RxBus.getDefault().post(new MoreViewChangeEvent(MoreViewChangeEvent.MORE_VIE_HOME));
                }
                break;
        }
    }

    @Override
    public void showChangeShiftSuccess(String result) {

    }

    @Override
    public void showAddPersonShiftSuccess(String result) {
        mServerAdapter.clearSelect();
        mPresenter.getScheduleDetail(scheduleView.getSelectedDate());
    }

    @Override
    public void showRemovePersonShiftSuccess(String result) {
        mPresenter.getScheduleDetail(scheduleView.getSelectedDate());
    }

    @Override
    public void showServerList(List<ServerEntity> servers) {
        shopServerList = servers;
    }

    @Override
    public void showCheckDoChangeShiftSuccess() {
        closeDialog(mEmployeeDialog);
        ACT_ChangeShift.startAc(mContext,
                scheduleView.getSelectedDate(), mSelectedSchedule, mSelectedEmployee);
    }

    @Override
    protected void onUserVisible() {

    }

    public void setInActivity(boolean inActivity) {
        this.inActivity = inActivity;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeDialog(mEmployeeDialog, mAddEmployeeToShiftDialog);
    }

    @Override
    public void showError(String msg) {
        super.showError(msg);

        if(mEmployeeDialog!=null && mEmployeeDialog.isShowing()){
            btnRemove.stopLoading("移除");
        }

        if (mAddEmployeeToShiftDialog != null && mAddEmployeeToShiftDialog.isShowing()) {
            LoadingButton lbConfirm = mAddEmployeeToShiftDialog.getView(R.id.lb_confirm);
            lbConfirm.stopLoading("确定");
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.fra_schedule;
    }

}
